#pragma once

#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Err.hpp"
#include "Log.hpp"

const int defaultSockfd = -1;
const int gbacklog = 5;

class Sock
{
public:
    Sock() : _sockfd(defaultSockfd){}

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            logMessage(Fatal, "sockfd create error,code:%d,error:%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        logMessage(Info, "socket create successful");
    }
    void Bind(const uint16_t &port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = INADDR_ANY;
        if (bind(_sockfd, reinterpret_cast<struct sockaddr *>(&server), sizeof(server)) != 0)
        {
            logMessage(Fatal, "sockfd Bind error,code:%d,error:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        logMessage(Info, "socket Bind successful");
    }
    void Listen()
    {
        int ret = listen(_sockfd, gbacklog);
        if (ret != 0)
        {
            logMessage(Fatal, "sockfd Listen error,code:%d,error:%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
        logMessage(Info, "socket Listen successful");
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        socklen_t len = sizeof(client);
        int sockfd = accept(_sockfd, reinterpret_cast<struct sockaddr *>(&client), &len);
        if (sockfd < 0)
        {
            logMessage(Warning, "sockfd accept error,code:%d,error:%s", errno, strerror(errno));
            return -1;
        }
        logMessage(Info, "socket accept successful, get new sockfd:%d", sockfd);
        *clientip = inet_ntoa(client.sin_addr);
        *clientport = ntohs(client.sin_port);
        return sockfd;
    }

    int Connect(const std::string &serverip, const uint16_t &serverport)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());
        return connect(_sockfd,reinterpret_cast<struct sockaddr*>(&server),sizeof(server));
    }
    inline int Fd()
    {
        return _sockfd;
    }

    ~Sock() 
    {
        if(_sockfd!=defaultSockfd)close(_sockfd);
    }

private:
    int _sockfd;
};